<script setup lang="ts">
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { ApiApi } from '#/api/system/api';
import type { SystemApi } from '#/api/system/system';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { ElButton, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteApi, getApiList } from '#/api/system/api';
import { EditInfo } from '#/components/edit-info/index';
import { $t } from '#/locales';
import {
  useApiGridColumns,
  useApiGridFormSchema,
} from '#/views/system/api/data';

import ApiForm from './components/apiForm.vue';

interface Props {
  systemData?: SystemApi.System;
}

const props = defineProps<Props>();

const emit = defineEmits(['close']);

const systemInfo = ref<SystemApi.System>();

const title = computed(() => {
  const systemName = systemInfo.value?.name || props.systemData?.name || '';
  return `API管理 - ${systemName}`;
});

/** 刷新表格 */
function onApiRefresh() {
  apiGridApi.query();
}

function onApiEdit(row: ApiApi.Api) {
  apiFormDrawerApi.setData(row).open();
}

function onApiCreate() {
  if (!systemInfo.value?.id && !props.systemData?.id) {
    ElMessage.error('系统信息获取失败');
    return;
  }
  apiFormDrawerApi
    .setData({
      systemId: systemInfo.value?.id || props.systemData?.id,
    })
    .open();
}

/** 删除API */
async function onApiDelete(row: ApiApi.Api) {
  await ElMessageBox.confirm('确定要删除该API吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  await deleteApi(row.id as number);
  ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.title]));
  onApiRefresh();
}

const [ApiFormDrawer, apiFormDrawerApi] = useVbenDrawer({
  connectedComponent: ApiForm,
  destroyOnClose: true,
});

function onApiActionClick({ code, row }: OnActionClickParams<ApiApi.Api>) {
  switch (code) {
    case 'delete': {
      onApiDelete(row);
      break;
    }
    case 'edit': {
      onApiEdit(row);
      break;
    }
  }
}

const [ApiGrid, apiGridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useApiGridFormSchema(),
  },
  gridOptions: {
    columns: useApiGridColumns(onApiActionClick),
    height: 'auto',
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          const systemId = systemInfo.value?.id || props.systemData?.id;
          if (!systemId) {
            throw new Error('系统ID不能为空');
          }
          return await getApiList({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            systemId,
            ...formValues,
          });
        },
      },
    },
  } as VxeTableGridOptions<ApiApi.Api>,
});

// 获取抽屉API以便外部调用
const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-full max-w-none',
  appendToMain: true,
  destroyOnClose: true,
  async onConfirm() {
    // 绑定角色抽屉的确认操作 - 直接关闭抽屉
    await drawerApi.close();
  },
  onCancel() {
    emit('close');
    drawerApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      systemInfo.value = undefined;
      return;
    }
    // 从传入的数据中获取系统信息
    const data = drawerApi.getData<SystemApi.System>();
    if (data) {
      systemInfo.value = data;
    }
  },
});

// 暴露API供外部使用
defineExpose({
  drawerApi,
});
</script>

<template>
  <Drawer
    :title="title"
    :closable="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <ApiFormDrawer @success="onApiRefresh" />
    <ApiGrid table-title="API列表">
      <template #edit-info="{ row }">
        <EditInfo :handler-name="row.handlerName" :time="row.updateTime" />
      </template>
      <template #toolbar-tools>
        <ElButton
          type="primary"
          @click="onApiCreate"
          v-access:code="['system:system:add']"
        >
          <Plus class="mr-2 size-5" />
          {{ $t('ui.api.create') }}
        </ElButton>
      </template>
    </ApiGrid>
  </Drawer>
</template>
